package com.cheng.controller;

import com.alibaba.fastjson.JSONObject;
import com.cheng.service.FaceService.UserService;
import com.cheng.utli.RedisUtil;
import com.cheng.utli.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;



import static com.cheng.controller.Constant.*;

@Controller
@RequestMapping(value = "/Class")
public class ClassController   {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;


    private static final Logger logger = LoggerFactory.getLogger(ClassController.class);


    /**
     * 学生搜索cid
     * */
    @RequestMapping(value = "/searchCid" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject searchCid(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //获得学生openid
        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        //通过cid获得班级信息 1.查询redis缓存 2.查询
        String cid = request.getParameter("cid");
        //通过缓存获取
        JSONObject classInfo =JSONObject.parseObject((String) redisUtil.get(redisUtil.formatRedisKey(CLASS_KEY,cid)));
        if(!Utils.isNonBlank(classInfo)){
            classInfo = userService.getClassInfo(openId,cid);
            if(!Utils.isNonBlank(classInfo)){
                return setReturnObjInfo("fail","请输入正确的班级编码");
            }
        }
        //判断是否已经添加该cid
        if(Utils.isNotBlank(classInfo.getString("hasAdd"))&&classInfo.getString("hasAdd").equals("yes")){
            return setReturnObjInfo("hasAdd","用户已经添加本班级");
        }
        //存入缓存将查询的信息
        returnObj.put("resCode","100");
        redisUtil.set(redisUtil.formatRedisKey(CLASS_KEY,cid),classInfo.toString(), 1000L);
        returnObj.put("info",classInfo);
        return returnObj;
    }

    /**
     * 学生加入班集体操作
     * */
    @RequestMapping(value = "/joinClass" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject joinClass(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();
        //获得学生openid
        String openId = getSession(session);
        //获得班级编码
        String cid = request.getParameter("cid");
        //判断cid是否存在
        JSONObject classInfo = userService.getClassInfo(openId,cid);
        if(!Utils.isNonBlank(classInfo)){
            return setReturnObjInfo("fail","请输入正确的班级编码");
        }
        //判断是否已经添加该cid
        if(Utils.isNotBlank(classInfo.getString("hasAdd"))&&classInfo.getString("hasAdd").equals("yes")){
            return setReturnObjInfo("hasAdd","用户已经添加本班级");
        }

        //添加入表操作
        String result = userService.joinClass(openId,cid);
        if(Utils.isBlank(result)){
            return setReturnObjInfo("fail","添加失败");
        }
        returnObj.put("resInfo","加入班级成功");
        returnObj.put("resCode",100);

        //删除缓存
        redisUtil.remove(redisUtil.formatRedisKey(CLASS_KEY,cid));
        return  returnObj;
    }


    public String getSession(HttpSession session){
        String openid = (String) session.getAttribute("openId");
        if(Utils.isNotBlank(openid)){
            return openid;
        }
        return null;
    }

    public static JSONObject setReturnObjInfo(String resCode, String resInfo) {
        JSONObject result = new JSONObject();
        result.put("resCode",resCode);
        result.put("resInfo",resInfo);
        return result;
    }




    /**
     * 进行签到功能
     * */
    @RequestMapping(value = "/SignIn" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject signIn(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        //获得签到类型  1.开启人脸签到 2.开启随机密码签到  3.开启九宫格签到
        String type = request.getParameter("type");
        String cid = request.getParameter("cid");

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }

        if((type).contains("1,2,3")){
            return setReturnObjInfo("failParam","参数错误");
        }

        String key = redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid);
        //查看过期时间
        if(!redisUtil.exists(key)){
            returnObj.put("noSignInTime","不在签到时间");
            return returnObj;
        }
        if(type.equals("1")){
            //todo:获得用户拍照的照片
        }
        else{
            //获得学生输入的密码
            String password = request.getParameter("password");
            //获取缓存的密码
            String redisPassword = redisUtil.getString(redisUtil.formatRedisKey(CLASS_SIGN_KEY_PASSWORD,cid));

            if(!redisPassword.equals(password)){
                returnObj.put("resCode","passWordError");
                returnObj.put("resInfo","签到密码错误，请重新输入");
                return returnObj;
            }
            //修改签到状态  根据本次签到次数，学生openid进行修改
            userService.updateSignInfo(openId,cid);
            //删除缓存
            redisUtil.remove(redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid,openId));
            returnObj.put("resCode","100");
            return returnObj;
        }

        return returnObj;
    }

    /**
     * 签到页面实时刷新
     * */
    @RequestMapping(value = "/updateSignInPage" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject updateSignInPage(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String cid = request.getParameter("cid");
        String type = request.getParameter("type");

        String key = redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid,type);
        if(!redisUtil.exists(key)){
            returnObj.put("noSignInTime","不在签到时间");
            return returnObj;
        }
        //返回用户修改状态
        returnObj.put("info",userService.getUserSignInfo(cid));

        return returnObj;
    }

    /**
     * 用户查询当前班级签到记录
     * */
    @RequestMapping(value = "/queryClassSignInInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject queryClassSignInInfo(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }

        String cid = request.getParameter("cid");

        String key = redisUtil.formatRedisKey(CLASS_SIGN_KEY,cid,openId);

        JSONObject userInfo = (JSONObject) redisUtil.getJson(key);


        if(userInfo != null){
            userInfo = userService.queryClassSignInInfo(cid,openId);
            //得到的数据存入缓存
            redisUtil.set(key,userInfo.toString(), 600L);
        }
        returnObj.put("suc","100");
        returnObj.put("signInfo",userInfo);
        return returnObj;
    }

    /**
     * 查询用户的所有请假记录
     * */
    @RequestMapping(value = "/getUserAllLeaveInfo" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserAllLeaveInfo(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }

        String key = redisUtil.formatRedisKey(USER_GET_ALL_LEAVE_INFO,openId);

        JSONObject leaveList = redisUtil.getJson(key);

        if(leaveList ==null){
            leaveList = userService.getUserAllLeaveInfo(openId);
            redisUtil.set(key,leaveList.toString(),600L);
            logger.error("得到的leaveList的信息"+leaveList.toString());
        }
        returnObj.put("suc","100");
        returnObj.put("leaveList",leaveList);
        return  returnObj;
    }
    /**
     * 用户请假操作
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/userLeaveHandler" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject userLeaveHandler(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        String leaveInfo =  request.getParameter("leaveInfo");
        //todo：得到上传的网络图片链接
        String leavePhoto = request.getParameter("leavePhoto");
        String cid = request.getParameter("cid");


        //进行请假操作
        HashMap map = new HashMap<String,String>();

        map.put("reason",leaveInfo);
        map.put("photo",leavePhoto);
        map.put("openId",openId);
        map.put("cid",cid);


        try {
            userService.userLeaveHandler(map);
        } catch (Exception e) {
            returnObj.put("fail","-100");
            e.printStackTrace();
        }
        returnObj.put("suc","100");

        return returnObj;
    }

    /**
     * 获得用户加入的班级
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserJoinClass" ,produces="text/html;charset=UTF-8")
    @ResponseBody
    public JSONObject getUserJoinClass(HttpSession session, HttpServletRequest request){
        JSONObject returnObj = new JSONObject();

        String openId = getSession(session);
        if(Utils.isBlank(openId)){
            return setReturnObjInfo("-100","没有登录");
        }
        returnObj.put("classList", userService.getUserJoinClass(openId));
        returnObj.put("suc","100");
        return returnObj;
    }
}
